package com.daiyang.campus_lucky_draw.service.impl;

import com.daiyang.campus_lucky_draw.contreller.param.CreatePrizeParam;
import com.daiyang.campus_lucky_draw.contreller.param.PageListParam;
import com.daiyang.campus_lucky_draw.mapper.DO.PrizeDO;
import com.daiyang.campus_lucky_draw.mapper.PrizeMapper;
import com.daiyang.campus_lucky_draw.service.PictureService;
import com.daiyang.campus_lucky_draw.service.PrizeService;
import com.daiyang.campus_lucky_draw.service.dto.PageListDTO;
import com.daiyang.campus_lucky_draw.service.dto.PrizeDTO;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class PrizeServiceImpl implements PrizeService {
    private static final Logger logger =
            LoggerFactory.getLogger(PrizeServiceImpl.class);
    @Autowired
    private PrizeMapper prizeMapper;
    @Autowired
    private PictureService pictureService;
    @Override
    public Long createPrize(CreatePrizeParam param, MultipartFile prizePic) {
        PrizeDO prizeDO = new PrizeDO();
        prizeDO.setName(param.getPrizeName());
        prizeDO.setDescription(param.getDescription());
        prizeDO.setPrice(param.getPrice());
        // 保存图⽚
        String fileName = pictureService.savePicture(prizePic);
        prizeDO.setImageUrl(fileName);
        prizeMapper.insert(prizeDO);
        return prizeDO.getId();
    }

    @Override
    public PageListDTO<PrizeDTO> findPrizeList(PageListParam param) {
        int count = prizeMapper.count();
        List<PrizeDO> prizes =
                prizeMapper.queryPrizesByPage(param.offset(),
                        param.getPageSize());
        List<PrizeDTO> records = new ArrayList<>();
        for (PrizeDO prizeDO : prizes) {
            PrizeDTO prizeDTO = new PrizeDTO();
            prizeDTO.setId(prizeDO.getId());
            prizeDTO.setName(prizeDO.getName());
            prizeDTO.setDescription(prizeDO.getDescription());
            prizeDTO.setPrice(prizeDO.getPrice());
            prizeDTO.setImageUrl(prizeDO.getImageUrl());
            records.add(prizeDTO);
        }
        return new PageListDTO(count, records);
    }


}